<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>{{ title }}</span>
      </div>
      <el-form ref="form" :model="questionForm" :rules="rules" label-width="80px">
        <el-form-item label="学科" prop="subjectID">
          <el-select v-model="questionForm.subjectID" style="width: 400px;" @change="getCatalogAndTagsList">
            <el-option v-for="item in subjects" :key="item.id" :label="item.subjectName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="目录" prop="catalogID">
          <el-select v-model="questionForm.catalogID" style="width: 400px;">
            <el-option v-for="item in catalogs" :key="item.id" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="企业" prop="enterpriseID">
          <el-select v-model="questionForm.enterpriseID" style="width: 400px;">
            <el-option v-for="item in companys" :key="item.id" :label="item.company" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市">
          <el-select v-model="questionForm.province" style="width: 190px; margin-right: 20px;" prop="province" @change="choseProvince">
            <el-option v-for="(item, index) in provinceList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
          <el-select v-model="questionForm.city" style="width: 190px;" prop="province">
            <el-option v-for="(item, index) in cityList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="方向" prop="direction">
          <el-select v-model="questionForm.direction" style="width: 400px;">
            <el-option v-for="(item, index) in directionList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题型" prop="questionType">
          <el-radio-group v-model="questionForm.questionType">
            <el-radio v-for="item in questionTypeList" :key="item.value" :label="item.value" @change="reastCheckbox">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-radio-group v-model="questionForm.difficulty">
            <el-radio v-for="item in difficultyList" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题干" prop="question">
          <quill-editor v-model="questionForm.question" :options="editorOption" />
        </el-form-item>

        <!-- 单选 -->
        <el-form-item label="选项" v-if="this.questionForm.questionType === 1">
          <el-radio-group v-model="radio">
            <div class="radio-group" v-for="(item, index) in questionForm.options" :key="index">
              <el-radio :label="item.isRight" @change="choseRadio(index)">{{ item.code }}:</el-radio>
              <el-input type="text" v-model="item.title" style="width:280px;"></el-input>
              <el-upload
                action="#"
                :auto-upload="false"
                class="avatar-uploader"
                :show-file-list="false"
                :on-change="
                  file => {
                    handleChange(file, index)
                  }
                "
              >
                <img v-if="item.img" :src="item.img" class="avatar" />
                <i v-else class="words" style="font-size:12px;">上传图片</i>
                <i  class="el-icon-circle-close" @click.stop="reastImg(index)"></i>
              </el-upload>
            </div>
          </el-radio-group>
        </el-form-item>

        <!-- 多选-->
        <el-form-item label="选项" v-else-if="this.questionForm.questionType === 2">
          <div class="checkbox-group" v-for="(item, index) in questionForm.options" :key="index">
            <el-checkbox v-model="item.isRight" :label="numToLetter(index)">{{ item.code }}:</el-checkbox>
            <el-input type="text" v-model="item.title" style="width:280px;"></el-input>
            <el-upload action="#" class="avatar-uploader" :show-file-list="false"   :auto-upload="false" :on-change="
                  file => {
                    handleChange(file, index)
                  }
                ">
              <img v-if="item.img" :src="item.img" class="avatar" />
              <i v-else class="words" style="font-size:12px;">上传图片</i>
              <i  class="el-icon-circle-close" @click.stop="reastImg(index)"></i>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="danger" size="small" :disabled="questionForm.questionType === 1" @click="addAnswer">+增加选项与答案</el-button>
        </el-form-item>
        <el-form-item label="解析视频">
          <el-input v-model="questionForm.videoURL" style="width: 400px;"></el-input>
        </el-form-item>

        <el-form-item label="答案解析" prop="answer">
          <quill-editor  ref="remarkEditor" v-model="questionForm.answer" :options="editorOption"></quill-editor>
        </el-form-item>
        <el-form-item label="题目备注">
          <el-input type="textarea" v-model="questionForm.remarks" style="width: 400px;"></el-input>
        </el-form-item>

        <el-form-item label="试题标签">
          <el-select v-model="questionForm.tags" multiple style="width: 400px;">
            <el-option v-for="item in tagsList" :key="item.value" :label="item.label" :value="item.label"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-if="!id" type="primary" @click="addQuestion">确认提交</el-button>
          <el-button v-else type="success" @click="addQuestion">确认修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { list } from '@/api/hmmm/subjects' // 学科列表
import { simple } from '@/api/hmmm/directorys' // 目录列表
import { simple as tagsList } from '@/api/hmmm/tags' // 标签列表
import { list as companysList } from '@/api/hmmm/companys' // 公司列表
import { add, detail, update } from '@/api/hmmm/questions' // 添加题目，题目详情，修改题目
import { provinces, citys } from '@/api/hmmm/citys' // 省市列表
import { direction, questionType, difficulty } from '@/api/hmmm/constants' // 方向，题目类型，难度
export default {
  components: { quillEditor },

  data () {
    return {
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            ['blockquote', 'code-block'], // 引用，代码块
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序列表，无序列表
            ['link', 'image', 'video'] // 链接、图片、视频-----
          ]
        }
      }, // 文本剪辑器配置
      id: this.$route.query.id,
      title: '',
      questionForm: {
        subjectID: '',
        catalogID: '',
        enterpriseID: '',
        province: '', // 城市
        city: '', // 地区
        direction: '',
        questionType: 1,
        difficulty: 1,
        question: '',
        options: [
          { code: 'A', isRight: false, title: '', img: '' },
          { code: 'B', isRight: false, title: '', img: '' },
          { code: 'C', isRight: false, title: '', img: '' },
          { code: 'D', isRight: false, title: '', img: '' }
        ],
        videoURL: '',
        answer: '',
        remarks: '',
        tags: ''
      },
      rules: {
        subjectID: [{ required: true, message: '请选择学科', trigger: 'blur' }],
        catalogID: [{ required: true, message: '请选择目录', trigger: 'blur' }],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'blur' }],
        province: [{ required: true, message: '请选择城市', trigger: 'blur' }],
        city: [{ required: true, message: '请选择地区', trigger: 'blur' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'blur' }],
        questionType: [{ required: true, message: '请选择题型', trigger: 'blur' }],
        difficulty: [{ required: true, message: '请选择难度', trigger: 'blur' }],
        question: [{ required: true, message: '请输入题干', trigger: 'blur' }],
        answer: [{ required: true, message: '请输入答案解析', trigger: 'blur' }]
      },
      subjects: [], // 学科列表
      catalogs: [], // 目录列表
      companys: [], // 企业列表
      tagsList: [], // 标签列表
      provinceList: provinces(), // 省份列表
      cityList: [], // 城市列表
      directionList: direction, // 方向列表
      questionTypeList: questionType, // 题型列表
      difficultyList: difficulty, // 难度列表
      radio: null
    }
  },
  created () {
    this.changeTitle()
    this.getSubjectList()
    this.getCompanyList()
  },

  methods: {
    async changeTitle () {
      if (this.id) {
        this.title = '试题修改'
        const res = await detail({ id: this.id })
        this.questionForm = res.data
        this.getCatalogAndTagsList()
        if (this.questionForm.tags) {
          this.questionForm.tags = this.questionForm.tags.split(',')
        }
        this.questionForm.difficulty = +this.questionForm.difficulty
        this.questionForm.questionType = +this.questionForm.questionType
        this.questionForm.options.forEach(item => {
          if (item.isRight === 1) {
            item.isRight = true
            this.radio = item.isRight
          }
        })
        this.$nextTick(function () {
          window.scrollTo(0, 0)
        })
        console.log(this.$route)
      } else {
        this.title = '新增试题'
      }
    },

    // 获取学科列表
    async getSubjectList () {
      const res = await list()
      this.subjects = res.data.items
    },
    // 获取目录和标签列表
    async getCatalogAndTagsList () {
      const res = await simple({ subjectID: this.questionForm.subjectID })
      this.catalogs = res.data
      const res1 = await tagsList({ subjectID: this.questionForm.subjectID })
      this.tagsList = res1.data
    },
    // 获取企业列表
    async getCompanyList () {
      const res = await companysList()
      this.companys = res.data.items
    },
    // 获取城市列表
    choseProvince (val) {
      this.cityList = citys(val)
    },
    // 单选
    choseRadio (index) {
      this.questionForm.options.forEach(item => {
        item.isRight = false
      })
      this.questionForm.options[index].isRight = true
      this.radio = this.questionForm.options[index].isRight
    },
    // 重置选项框
    reastCheckbox () {
      this.questionForm.options.forEach(item => {
        item.isRight = false
      })
    },
    // 添加题目
    async addQuestion () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (this.questionForm.tags.length === 0) {
            this.questionForm.tags = ''
          } else {
            this.questionForm.tags = this.questionForm.tags.join(',')
          }
          this.questionForm.difficulty = this.questionForm.difficulty.toString()
          this.questionForm.questionType = this.questionForm.questionType.toString()
          if (this.id) {
            console.log(this.id)
            const res = await update(this.questionForm)
            if (res.status === 200) {
              this.$message.success('修改成功')
              this.$router.go(-1)
            }
          } else {
            const res1 = await add(this.questionForm)
            if (res1.status === 200) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.$router.push({ name: 'questions-list' })
            }
          }
        }
      })
    },
    // 数字转字母
    numToLetter (num) {
      return String.fromCharCode(65 + num)
    },
    // 增加选项与答案
    addAnswer () {
      const code = this.numToLetter(this.questionForm.options.length)
      this.questionForm.options.push({ code: code, isRight: '', title: '', img: '' })
    },
    // 显示图片
    handleChange (file, index) {
      this.questionForm.options[index].img = file.raw // 图片文件
      this.questionForm.options[index].img = URL.createObjectURL(file.raw)
    },
    reastImg (index) {
      this.questionForm.options[index].img = ''
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .ql-editor {
  height: 200px;
}
.radio-group,
.checkbox-group {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  // overflow: hidden;
  margin-left: 5px;
  height: 60px;
  width: 100px;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.words {
  font-style: normal;
  font-size: 18px;
  color: #8c939d;
  width: 18px;
  height: 18px;
  line-height: 60px;
  text-align: center;
}
.el-icon-circle-close {
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  height:58px;
  width: 98px;
  display: block;
}
::v-deep .el-radio,
::v-deep .el-checkbox {
  margin-right: 10px;
}
.checkbox-group {
  margin-bottom: 20px;
  line-height: 0;
}
</style>
